package com.thread.threadpool;

import java.io.IOException;
import java.util.concurrent.*;

/**
 * @author: mayu
 * @date: 2021年04月16日 14:19
 * 自定义线程池
 */
public class TestThreadPoolExecutor {
    public static void main(String[] args) {
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(2,
                4,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(4),
                new MyThreadFactory("xxx ye wu"),
                //Executors.defaultThreadFactory(),
                //new ThreadPoolExecutor.AbortPolicy());//线程池满了会抛出异常
                //new ThreadPoolExecutor.DiscardPolicy());//线程池满了会悄悄扔掉后续来的任务，不抛出异常
                //new ThreadPoolExecutor.DiscardOldestPolicy());//线程池满了会扔掉等待时间最长的任务，把新来的放进任务队列
                new ThreadPoolExecutor.CallerRunsPolicy());//线程池满了会直接使用调用者线程执行后续的任务

        for (int i = 0; i < 8; i++) {
            tpe.execute(new MyTask(i));
        }

        System.out.println(tpe);
        System.out.println(tpe.getQueue());

        tpe.execute(new MyTask(100));

        System.out.println(tpe.getQueue());
        tpe.shutdown();
    }

    static class MyTask implements Runnable {
        private int i;

        public MyTask(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "-Task--" + i);
            try {
                System.in.read();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public String toString() {
            return "MyTask{" +
                    "i=" + i +
                    '}';
        }
    }
}
